package com.example.myapplication;
//C:\Users\liuzc\Desktop\MyApplication2\app\src\main\java\com\example\myapplication\MainActivity.java
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.media.SoundPool;
import android.media.AudioAttributes;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    // 音效相关变量
    private SoundPool soundPool;
    private int hitSoundId;
    private int startSoundId;
    private int currentSoundStreamId = -1; // 新增：当前播放的音效流ID（用于暂停）

    // 地鼠任务管理（核心修复：用Handler和Runnable控制地鼠任务，支持取消）
    private Handler moleHandler = new Handler();
    private Runnable moleRunnable;

    private GridLayout gridLayout;
    private TextView scoreTextView, timeTextView;
    private Button startButton, settingsButton, pauseButton;
    private ImageView[] holes;
    private Random random;
    private int score = 0;
    private boolean isPlaying = false;
    private boolean isPaused = false;
    private CountDownTimer gameTimer;
    private long remainingTime = 30000; // 剩余时间（毫秒）
    private int[] moleImages = {R.drawable.mole1, R.drawable.mole2, R.drawable.mole3};
    private int rowCount = 3;
    private int columnCount = 3;
    private int num_of_holes = rowCount * columnCount;
    private int gameTime = 30; // 游戏时间（秒）

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化控件
        gridLayout = findViewById(R.id.gridLayout);
        scoreTextView = findViewById(R.id.scoreTextView);
        timeTextView = findViewById(R.id.timeTextView);
        startButton = findViewById(R.id.startButton);
        settingsButton = findViewById(R.id.settingsButton);
        pauseButton = findViewById(R.id.pauseButton);

        random = new Random();
        holes = new ImageView[num_of_holes];

        // 初始化音效池
        initSoundPool();

        setupHoles();

        // 按钮点击事件
        startButton.setOnClickListener(v -> startGame());
        settingsButton.setOnClickListener(v -> showSettingsDialog());
        pauseButton.setOnClickListener(v -> pauseGame()); // 暂停逻辑独立为方法
    }

    // -------------------------- 1. 核心修复：暂停游戏逻辑（完全停止所有任务） --------------------------
    private void pauseGame() {
        if (!isPlaying || isPaused) return;

        // 1.1 标记为暂停状态
        isPaused = true;
        pauseButton.setText("恢复游戏"); // 按钮文本切换为“恢复”

        // 1.2 停止倒计时器（关键：防止时间继续流逝）
        if (gameTimer != null) {
            gameTimer.cancel();
            gameTimer = null;
        }

        // 1.3 取消地鼠显示任务（关键：防止地鼠继续弹出）
        if (moleRunnable != null) {
            moleHandler.removeCallbacks(moleRunnable);
        }

        // 1.4 停止所有正在播放的音效（关键：防止音乐继续）
        if (soundPool != null && currentSoundStreamId != -1) {
            soundPool.stop(currentSoundStreamId);
            currentSoundStreamId = -1; // 重置流ID
        }

        // 1.5 隐藏当前地鼠（视觉上暂停）
        hideAllMoles();

        // 1.6 显示暂停对话框
        showPauseDialog();
    }

    // -------------------------- 2. 修复：暂停对话框（选项逻辑与状态同步） --------------------------
    private void showPauseDialog() {
        new AlertDialog.Builder(this)
                .setTitle("游戏暂停")
                .setMessage("当前分数：" + score + "\n剩余时间：" + remainingTime / 1000 + "秒")
                .setCancelable(false) // 不可点击外部关闭，避免误操作
                .setPositiveButton("继续游戏", (dialog, which) -> resumeGame())
                .setNeutralButton("结束本轮", (dialog, which) -> endCurrentGame())
                .setNegativeButton("退出游戏", (dialog, which) -> finish())
                .show();
    }

    // -------------------------- 3. 修复：恢复游戏逻辑（重新启动所有任务） --------------------------
    private void resumeGame() {
        if (!isPlaying || !isPaused) return;

        // 3.1 标记为非暂停状态
        isPaused = false;
        pauseButton.setText("暂停游戏");

        // 3.2 重启倒计时器（使用剩余时间）
        gameTimer = new CountDownTimer(remainingTime, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                remainingTime = millisUntilFinished;
                timeTextView.setText("时间: " + millisUntilFinished / 1000 + "秒");
            }

            @Override
            public void onFinish() {
                endCurrentGame();
            }
        }.start();

        // 3.3 重启地鼠显示任务
        showRandomMole();
    }

    // -------------------------- 4. 核心修复：地鼠显示逻辑（用Runnable绑定任务，支持取消） --------------------------
    private void showRandomMole() {
        if (!isPlaying || isPaused) return;

        // 4.1 先隐藏所有地鼠
        hideAllMoles();

        // 4.2 随机选择地鼠位置和图片
        int randomIndex = random.nextInt(num_of_holes);
        int randomImage = moleImages[random.nextInt(moleImages.length)];
        holes[randomIndex].setImageResource(randomImage);
        holes[randomIndex].setTag("mole");

        // 4.3 播放地鼠出现音效（记录流ID，用于暂停时停止）
        currentSoundStreamId = soundPool.play(startSoundId, 1.0f, 1.0f, 1, 0, 1.0f);

        // 4.4 计算地鼠显示时间（适配网格大小）
        int delay = 500 + random.nextInt(1000) + (num_of_holes * 20);

        // 4.5 绑定地鼠隐藏任务到Runnable（关键：可被Handler取消）
        moleRunnable = new Runnable() {
            @Override
            public void run() {
                if (isPlaying && !isPaused) { // 仅在游戏进行中且未暂停时执行
                    holes[randomIndex].setImageResource(0);
                    holes[randomIndex].setTag(null);
                    showRandomMole(); // 递归调用，继续显示下一个地鼠
                }
            }
        };

        // 4.6 延迟执行地鼠隐藏任务
        moleHandler.postDelayed(moleRunnable, delay);
    }

    // -------------------------- 5. 修复：开始游戏逻辑（初始化所有任务状态） --------------------------
    private void startGame() {
        if (isPlaying && !isPaused) return;

        // 5.1 重置所有状态
        score = 0;
        isPlaying = true;
        isPaused = false;
        remainingTime = gameTime * 1000L;
        scoreTextView.setText("分数: 0");
        timeTextView.setText("时间: " + gameTime + "秒");
        startButton.setText("游戏进行中...");
        pauseButton.setEnabled(true);
        pauseButton.setText("暂停游戏");

        // 5.2 清除残留的地鼠任务（防止多次点击开始导致任务叠加）
        if (moleRunnable != null) {
            moleHandler.removeCallbacks(moleRunnable);
        }

        // 5.3 启动倒计时器
        gameTimer = new CountDownTimer(remainingTime, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                remainingTime = millisUntilFinished;
                timeTextView.setText("时间: " + millisUntilFinished / 1000 + "秒");
            }

            @Override
            public void onFinish() {
                endCurrentGame();
            }
        }.start();

        // 5.4 启动地鼠显示
        showRandomMole();
    }

    // -------------------------- 6. 修复：结束本轮逻辑（彻底清理所有任务） --------------------------
    private void endCurrentGame() {
        // 6.1 重置游戏状态
        isPlaying = false;
        isPaused = false;

        // 6.2 停止倒计时器
        if (gameTimer != null) {
            gameTimer.cancel();
            gameTimer = null;
        }

        // 6.3 取消地鼠任务
        if (moleRunnable != null) {
            moleHandler.removeCallbacks(moleRunnable);
        }

        // 6.4 停止音效
        if (soundPool != null && currentSoundStreamId != -1) {
            soundPool.stop(currentSoundStreamId);
            currentSoundStreamId = -1;
        }

        // 6.5 隐藏地鼠+更新UI
        hideAllMoles();
        timeTextView.setText("时间到!");
        startButton.setText("再来一局");
        pauseButton.setEnabled(false);

        // 6.6 提示结果
        Toast.makeText(this, "本轮结束！最终分数：" + score, Toast.LENGTH_SHORT).show();
    }

    // -------------------------- 7. 修复：地鼠点击逻辑（暂停时禁止点击） --------------------------
    private View.OnClickListener moleClickListener = v -> {
        // 暂停或未游戏时，点击无效（关键：防止暂停后误触加分）
        if (!isPlaying || isPaused) return;

        ImageView clickedHole = (ImageView) v;
        if ("mole".equals(clickedHole.getTag())) {
            score++;
            scoreTextView.setText("分数: " + score);
            clickedHole.setImageResource(R.drawable.hit);
            clickedHole.setTag(null);

            // 播放击中音效（记录流ID）
            if (soundPool != null) {
                currentSoundStreamId = soundPool.play(hitSoundId, 1.0f, 1.0f, 1, 0, 1.0f);
            }

            // 取消当前地鼠的隐藏任务（点击后立即消失，不再等待延迟）
            if (moleRunnable != null) {
                moleHandler.removeCallbacks(moleRunnable);
                // 立即显示下一个地鼠
                moleHandler.postDelayed(this::showRandomMole, 200); // 200ms延迟，避免切换太快
            }
        }
    };

    // -------------------------- 原有逻辑（保持不变） --------------------------
    private void initSoundPool() {
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_GAME)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();

        soundPool = new SoundPool.Builder()
                .setAudioAttributes(audioAttributes)
                .setMaxStreams(5)
                .build();

        // 加载音效（确保资源文件存在，路径正确）
        hitSoundId = soundPool.load(this, R.raw.hit, 1);
        startSoundId = soundPool.load(this, R.raw.start, 1);
    }

    private void setupHoles() {
        gridLayout.setRowCount(rowCount);
        gridLayout.setColumnCount(columnCount);

        for (int i = 0; i < num_of_holes; i++) {
            holes[i] = new ImageView(this);
            int row = i / columnCount;
            int col = i % columnCount;

            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.rowSpec = GridLayout.spec(row);
            params.columnSpec = GridLayout.spec(col);

            // 动态计算地鼠大小（适配屏幕）
            int size = getResources().getDisplayMetrics().widthPixels / (columnCount + 1);
            params.width = size;
            params.height = size;
            params.setMargins(5, 5, 5, 5);

            holes[i].setLayoutParams(params);
            holes[i].setBackgroundResource(R.drawable.hole);
            holes[i].setOnClickListener(moleClickListener);
            gridLayout.addView(holes[i]);
        }
    }

    private void hideAllMoles() {
        for (ImageView hole : holes) {
            hole.setImageResource(0);
            hole.setTag(null);
        }
    }

    private void showSettingsDialog() {
        if (isPlaying && !isPaused) {
            Toast.makeText(this, "请先结束当前游戏或暂停游戏", Toast.LENGTH_SHORT).show();
            return;
        }

        View dialogView = getLayoutInflater().inflate(R.layout.settings_dialog, null);

        // 行列数控件
        Button rowMinusBtn = dialogView.findViewById(R.id.rowMinusBtn);
        Button rowPlusBtn = dialogView.findViewById(R.id.rowPlusBtn);
        TextView rowValueTv = dialogView.findViewById(R.id.rowValueTv);
        Button colMinusBtn = dialogView.findViewById(R.id.colMinusBtn);
        Button colPlusBtn = dialogView.findViewById(R.id.colPlusBtn);
        TextView colValueTv = dialogView.findViewById(R.id.colValueTv);

        // 时间设置控件
        Button timeMinusBtn = dialogView.findViewById(R.id.timeMinusBtn);
        Button timePlusBtn = dialogView.findViewById(R.id.timePlusBtn);
        TextView timeValueTv = dialogView.findViewById(R.id.timeValueTv);

        // 初始化显示当前设置
        rowValueTv.setText(String.valueOf(rowCount));
        colValueTv.setText(String.valueOf(columnCount));
        timeValueTv.setText(String.valueOf(gameTime));

        // 行数调整
        rowMinusBtn.setOnClickListener(v -> {
            int currentRow = Integer.parseInt(rowValueTv.getText().toString());
            if (currentRow > 2) {
                currentRow--;
                rowValueTv.setText(String.valueOf(currentRow));
            } else {
                Toast.makeText(MainActivity.this, "最少2行", Toast.LENGTH_SHORT).show();
            }
        });

        rowPlusBtn.setOnClickListener(v -> {
            int currentRow = Integer.parseInt(rowValueTv.getText().toString());
            if (currentRow < 5) {
                currentRow++;
                rowValueTv.setText(String.valueOf(currentRow));
            } else {
                Toast.makeText(MainActivity.this, "最多5行", Toast.LENGTH_SHORT).show();
            }
        });

        // 列数调整
        colMinusBtn.setOnClickListener(v -> {
            int currentCol = Integer.parseInt(colValueTv.getText().toString());
            if (currentCol > 2) {
                currentCol--;
                colValueTv.setText(String.valueOf(currentCol));
            } else {
                Toast.makeText(MainActivity.this, "最少2列", Toast.LENGTH_SHORT).show();
            }
        });

        colPlusBtn.setOnClickListener(v -> {
            int currentCol = Integer.parseInt(colValueTv.getText().toString());
            if (currentCol < 5) {
                currentCol++;
                colValueTv.setText(String.valueOf(currentCol));
            } else {
                Toast.makeText(MainActivity.this, "最多5列", Toast.LENGTH_SHORT).show();
            }
        });

        // 时间调整
        timeMinusBtn.setOnClickListener(v -> {
            int currentTime = Integer.parseInt(timeValueTv.getText().toString());
            if (currentTime > 20) {
                currentTime -= 5;
                timeValueTv.setText(String.valueOf(currentTime));
            } else {
                Toast.makeText(MainActivity.this, "最少20秒", Toast.LENGTH_SHORT).show();
            }
        });

        timePlusBtn.setOnClickListener(v -> {
            int currentTime = Integer.parseInt(timeValueTv.getText().toString());
            if (currentTime < 60) {
                currentTime += 5;
                timeValueTv.setText(String.valueOf(currentTime));
            } else {
                Toast.makeText(MainActivity.this, "最多60秒", Toast.LENGTH_SHORT).show();
            }
        });

        // 应用设置
        new AlertDialog.Builder(this)
                .setTitle("游戏设置")
                .setView(dialogView)
                .setPositiveButton("确定", (dialog, which) -> {
                    int newRows = Integer.parseInt(rowValueTv.getText().toString());
                    int newCols = Integer.parseInt(colValueTv.getText().toString());
                    int newTime = Integer.parseInt(timeValueTv.getText().toString());

                    if ((newRows < 2 || newRows > 5) ||
                            (newCols < 2 || newCols > 5) ||
                            (newTime < 20 || newTime > 60)) {
                        Toast.makeText(this, "数值超出范围", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 更新设置
                    rowCount = newRows;
                    columnCount = newCols;
                    gameTime = newTime;
                    remainingTime = gameTime * 1000L;
                    num_of_holes = rowCount * columnCount;

                    // 重建网格
                    gridLayout.removeAllViews();
                    holes = new ImageView[num_of_holes];
                    setupHoles();

                    // 更新时间显示
                    if (!isPlaying) {
                        timeTextView.setText("时间: " + gameTime + "秒");
                    }

                    Toast.makeText(this, "设置成功：" + rowCount + "x" + columnCount + "，" + gameTime + "秒", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    // -------------------------- 资源清理（防止内存泄漏） --------------------------
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清理倒计时器
        if (gameTimer != null) {
            gameTimer.cancel();
        }
        // 清理地鼠任务
        if (moleRunnable != null) {
            moleHandler.removeCallbacks(moleRunnable);
        }
        // 释放音效池
        if (soundPool != null) {
            soundPool.release();
            soundPool = null;
        }
        // 清理Handler（防止内存泄漏）
        moleHandler.removeCallbacksAndMessages(null);
    }
}